import React, { useState } from 'react';
import { Card, Table, Button, Space, Tag, Modal, Form, Input, Select, DatePicker, message, Typography, Row, Col } from 'antd';
import { BellOutlined, UserOutlined, ClockCircleOutlined, PlusOutlined, AlertOutlined, CheckCircleOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

const { Title, Text, Paragraph } = Typography;
const { Option } = Select;
const { RangePicker } = DatePicker;

interface EmergencyPatient {
  id: string;
  name: string;
  age: number;
  gender: string;
  condition: string;
  severity: 'critical' | 'serious' | 'stable';
  arrivalTime: string;
  waitingTime: string;
  status: 'waiting' | 'treating' | 'completed';
  assignedDoctor?: string;
}

// Mock 数据
const mockEmergencyPatients: EmergencyPatient[] = [
  {
    id: '1',
    name: '张三',
    age: 45,
    gender: '男',
    condition: '胸痛',
    severity: 'critical',
    arrivalTime: '2024-01-20 08:30',
    waitingTime: '15分钟',
    status: 'treating',
    assignedDoctor: '王医生'
  },
  {
    id: '2',
    name: '李四',
    age: 32,
    gender: '女',
    condition: '车祸外伤',
    severity: 'serious',
    arrivalTime: '2024-01-20 08:45',
    waitingTime: '0分钟',
    status: 'waiting'
  },
  {
    id: '3',
    name: '王五',
    age: 68,
    gender: '男',
    condition: '呼吸困难',
    severity: 'critical',
    arrivalTime: '2024-01-20 09:00',
    waitingTime: '0分钟',
    status: 'waiting'
  },
  {
    id: '4',
    name: '赵六',
    age: 28,
    gender: '男',
    condition: '高烧不退',
    severity: 'stable',
    arrivalTime: '2024-01-20 09:15',
    waitingTime: '30分钟',
    status: 'waiting'
  },
  {
    id: '5',
    name: '孙七',
    age: 55,
    gender: '女',
    condition: '脑出血',
    severity: 'critical',
    arrivalTime: '2024-01-20 08:00',
    waitingTime: '0分钟',
    status: 'completed',
    assignedDoctor: '李医生'
  },
];

const Emergency: React.FC = () => {
  const [patients, setPatients] = useState<EmergencyPatient[]>(mockEmergencyPatients);
  const [isAssignModalVisible, setIsAssignModalVisible] = useState(false);
  const [selectedPatient, setSelectedPatient] = useState<EmergencyPatient | null>(null);
  const [form] = Form.useForm();

  const severityColorMap = {
    critical: '#ff3b30',
    serious: '#ff9500',
    stable: '#34c759',
  };

  const severityTextMap = {
    critical: '危急',
    serious: '严重',
    stable: '稳定',
  };

  const statusColorMap = {
    waiting: '#8e8e93',
    treating: '#ff9500',
    completed: '#34c759',
  };

  const statusTextMap = {
    waiting: '等待',
    treating: '治疗中',
    completed: '已完成',
  };

  const columns: ColumnsType<EmergencyPatient> = [
    {
      title: '患者信息',
      dataIndex: ['name', 'age', 'gender'],
      key: 'patientInfo',
      render: (value, record) => (
        <Space direction="vertical">
          <Text strong>{record.name}</Text>
          <Text>{record.age}岁 · {record.gender}</Text>
        </Space>
      ),
    },
    {
      title: '病情',
      dataIndex: 'condition',
      key: 'condition',
    },
    {
      title: '严重程度',
      dataIndex: 'severity',
      key: 'severity',
      render: (severity) => (
        <Tag className="severity-tag" style={{ backgroundColor: severityColorMap[severity], color: 'white' }}>{severityTextMap[severity]}</Tag>
      ),
    },
    {
      title: '到达时间',
      dataIndex: 'arrivalTime',
      key: 'arrivalTime',
    },
    {
      title: '等待时间',
      dataIndex: 'waitingTime',
      key: 'waitingTime',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag className="status-tag" style={{ backgroundColor: statusColorMap[status], color: 'white' }}>{statusTextMap[status]}</Tag>
      ),
    },
    {
      title: '接诊医生',
      dataIndex: 'assignedDoctor',
      key: 'assignedDoctor',
      render: (doctor) => <Text className="doctor-name">{doctor || '未分配'}</Text>,
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          {record.status === 'waiting' && (
            <Button 
              type="primary" 
              size="small" 
              onClick={() => handleAssignDoctor(record)}
              className="apple-button-small"
            >
              接诊
            </Button>
          )}
          {record.status === 'treating' && (
            <Button 
              type="primary" 
              size="small" 
              danger 
              onClick={() => handleCompleteTreatment(record.id)}
              className="apple-button-small"
            >
              完成治疗
            </Button>
          )}
        </Space>
      ),
    },
  ];

  const handleAssignDoctor = (patient: EmergencyPatient) => {
    setSelectedPatient(patient);
    form.setFieldsValue({
      assignedDoctor: '',
      treatmentPlan: '',
    });
    setIsAssignModalVisible(true);
  };

  const handleCompleteTreatment = (patientId: string) => {
    setPatients(patients.map(patient => 
      patient.id === patientId 
        ? { ...patient, status: 'completed' as const }
        : patient
    ));
    message.success('治疗已完成');
  };

  const handleAssignSubmit = () => {
    form.validateFields()
      .then(values => {
        if (selectedPatient) {
          setPatients(patients.map(patient => 
            patient.id === selectedPatient.id
              ? { 
                  ...patient, 
                  status: 'treating' as const, 
                  assignedDoctor: values.assignedDoctor 
                }
              : patient
          ));
          setIsAssignModalVisible(false);
          message.success(`已为患者${selectedPatient.name}分配医生`);
        }
      })
      .catch(info => {
        console.log('Validate Failed:', info);
      });
  };

  // 统计数据
  const totalPatients = patients.length;
  const waitingPatients = patients.filter(p => p.status === 'waiting').length;
  const treatingPatients = patients.filter(p => p.status === 'treating').length;
  const completedPatients = patients.filter(p => p.status === 'completed').length;
  const criticalPatients = patients.filter(p => p.severity === 'critical').length;

  return (
    <div className="emergency-dashboard apple-container">
      <div className="page-header">
        <Title level={2} className="page-title">
          <BellOutlined style={{ marginRight: 8 }} />
          急诊管理
        </Title>
      </div>

      {/* 统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }} className="stats-container">
        <Col xs={24} sm={12} md={8}>
          <Card className="apple-card stat-card">
            <Statistic 
              title="总患者数" 
              value={totalPatients} 
              prefix={<UserOutlined className="stat-icon" />}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={8}>
          <Card className="apple-card stat-card waiting-card">
            <Statistic 
              title="等待患者" 
              value={waitingPatients} 
              prefix={<ClockCircleOutlined className="stat-icon" />}
              valueStyle={{ color: '#ff9500' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={8}>
          <Card className="apple-card stat-card critical-card">
            <Statistic 
              title="危急患者" 
              value={criticalPatients} 
              prefix={<AlertOutlined className="stat-icon" />}
              valueStyle={{ color: '#ff3b30' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 患者列表 */}
      <Card className="apple-card patients-table-card" title="急诊患者列表" extra={
        <Button type="primary" icon={<PlusOutlined />} className="apple-button">新增患者</Button>
      }>
        <Table 
          columns={columns} 
          dataSource={patients} 
          rowKey="id" 
          pagination={false}
          rowClassName={(record) => {
            if (record.severity === 'critical') return 'critical-patient-row';
            if (record.severity === 'serious') return 'serious-patient-row';
            return '';
          }}
          className="emergency-table"
        />
      </Card>

      {/* 接诊分配模态框 */}
      <Modal
        title="接诊患者"
        open={isAssignModalVisible}
        onCancel={() => setIsAssignModalVisible(false)}
        footer={null}
        className="apple-modal"
      >
        {selectedPatient && (
          <Form
            form={form}
            layout="vertical"
            onFinish={handleAssignSubmit}
            className="allocation-form"
          >
            <Form.Item label="患者信息">
              <Text strong className="patient-info-text">{selectedPatient.name} - {selectedPatient.condition}</Text>
            </Form.Item>
            <Form.Item
              name="assignedDoctor"
              label="分配医生"
              rules={[{ required: true, message: '请选择医生' }]}
            >
              <Select placeholder="请选择医生" className="apple-select">
                <Option value="王医生">王医生</Option>
                <Option value="李医生">李医生</Option>
                <Option value="张医生">张医生</Option>
                <Option value="赵医生">赵医生</Option>
              </Select>
            </Form.Item>
            <Form.Item
              name="treatmentPlan"
              label="初步治疗方案"
            >
              <Input.TextArea rows={4} placeholder="请输入初步治疗方案" className="apple-textarea" />
            </Form.Item>
            <Form.Item>
              <Space style={{ float: 'right' }}>
                <Button onClick={() => setIsAssignModalVisible(false)} className="apple-button-secondary">
                  取消
                </Button>
                <Button type="primary" htmlType="submit" className="apple-button">
                  确认接诊
                </Button>
              </Space>
            </Form.Item>
          </Form>
        )}
      </Modal>
    </div>
  );
};

// 简单的统计组件
const Statistic: React.FC<{
  title: string;
  value: number | string;
  prefix?: React.ReactNode;
  valueStyle?: React.CSSProperties;
}> = ({ title, value, prefix, valueStyle }) => {
  return (
    <div className="statistic-container">
      <div className="statistic-title">{title}</div>
      <div className="statistic-content">
        {prefix && <span className="statistic-prefix">{prefix}</span>}
        <span className="statistic-value apple-stat-value" style={valueStyle}>{value}</span>
      </div>
    </div>
  );
};

export default Emergency;